//引入生成用户唯一标识
import userTempId from "@/utils/userTempId"

import {
    requestLogin,
    requestUserInfo,
    requestLogout
} from "@/api" //引入登录请求的api

//保存用户信息的模块
const state = {
    userTempId : userTempId(),
    token: localStorage.getItem("user_token") || "" ,
    nikeName: ""
}
const mutations = {
    //登录保存token
    SET_TOKEN_STATE(state , value){
        state.token = value
    },

    //获取用户信息
    SET_NIKNAME_STATE(state , value){
        state.nikeName = value
    },

    //退出登录
    SET_LOGOUT_STATE(state){
        // console.log(11111);
        //清空vuex中的token
        state.token = "",
        //清空vuex中的nikeName
        state.nikeName = "",
        //清空本地存储中的token
        localStorage.removeItem("user_token")
    }


}

const actions = {
    //登录请求：拿到token
    async getLoginActions({commit} , userInfo){
        const result = await requestLogin(userInfo)
        commit("SET_TOKEN_STATE" , result.token)
        //拿到token后保存到本地存储
        localStorage.setItem("user_token" , result.token)
    },

    //获取用户信息请求：根据登录后的token请求用户信息
    async getUserInfoActions({commit}){
        try {
            const result = await requestUserInfo()
            commit("SET_NIKNAME_STATE" , result.nickName)
        } catch (error) {
            //在使用token发送请求的时候,如果token过期,则会抛出错误,被这里接受,我们可以清除掉token
            localStorage.removeItem("user_Token");
            //如果这里请求报错,则返回一个失败的promise实例,则dispatch方法就会返回这个失败的实例
            return Promise.reject();
        }
    },

    //退出登录请求
    async getLogout({commit}){
        await requestLogout()
        commit("SET_LOGOUT_STATE")
    }
   
}

const getters = {}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}